<?php

namespace addons\wangjian;

use app\common\library\Menu;
use think\Addons;

/**
 * 插件
 */
class Wangjian extends Addons
{

    private $appkey = null;
    private $appsecret = null;
    private $config = null;
    public function ConfigInit()
    {
        $this->config = $this->getConfig();

        $this->appkey = $this->config['appkey'];
        $this->appsecret = $this->config['appsecret'];
        $this->apiUrl = $this->config['apiUrl'];
    }
    /**
     * 短信发送通知
     * @param array $params
     * @return  boolean
     */
    public function smsSend(&$params)
    {
        $this->ConfigInit();

        $content = '您的验证码:'. $params['code'] .'，该验证码5分钟内有效，请勿泄漏于他人！';
        $url = $this->apiUrl . '/?Uid='. $this->appkey .'&Key='. $this->appsecret .'&smsMob='. $params['mobile'] .'&smsText='.$content;
        $result = $this->Get($url);
        if($result == 1){
            return true;
        }else{
            write_log($result,'短信发送错误');
            return false;
        }
    }

    private function Get($url)
    {
        $ch = curl_init();

        $timeout = 5;
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }

    /**
     * 检测验证是否正确
     * @param Sms $params
     * @return  boolean
     */
    public function smsCheck(&$params)
    {
        return true;
    }
    /**
     * 记录失败信息
     * @param [type] $err [description]
     */
    private function setError($err)
    {
        $this->sendError = $err;
    }

    /**
     * 获取失败信息
     * @return [type] [description]
     */
    public function getError()
    {
        return $this->sendError;
    }

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu = [
            [
                'name'   => 'Wangjian',
                'title'  => '创蓝短信插件',
                'ismenu' => 1,
                'icon'   => 'fa fa-list',
                'remark' => '',
            ]
        ];
        Menu::create($menu);
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete('Wangjian');
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable('Wangjian');
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable('Wangjian');
    }

    /**
     * 实现钩子方法
     * @return mixed
     */
    public function testhook($param)
    {
        // 调用钩子时候的参数信息
        print_r($param);
        // 当前插件的配置信息，配置信息存在当前目录的config.php文件中，见下方
        print_r($this->getConfig());
        // 可以返回模板，模板文件默认读取的为插件目录中的文件。模板名不能为空！
        //return $this->fetch('view/info');
    }

}
